"""

"""
from dotenv import load_dotenv,find_dotenv
from openai import OpenAI
import os
import json
from math import *
_ = load_dotenv(find_dotenv())

clinet = OpenAI(
    api_key = os.getenv("OPENAI_API_KEY"),
    base_url= os.getenv("OPENAI_API_BASE")
)

def get_completion(message,model = 'gpt-4'):
    response = clinet.chat.completions.create(
        model=model,
        messages=message,
        temperature=0,
        tools=[{
            'type':'function',
            'function':{
                'name':"calculate",
                "description": "计算一个数学表达式的值",
                "parameters":{
                    "type":'object',
                    "properties":{
                        "expression":{
                            "type":'string',
                            "description": "python语法中的一个数学表达式"
                        }
                    }
                }
            }
        }]
    )
    return response.choices[0].message

def startChat():
    prompt = '我有一个桃子，我把它分给三个人，每人可以吃掉1/3的桃子，请问桃子还剩多少？'
    message = [
        {
            "role":"system",
            "content":"你是一个数学家，你可以计算任何公式"
        },
        {
            "role":"user",  
            "content":prompt
        }
    ]
    response = get_completion(message)

    if(response.content is None):
        response.content = ''
    message.append(response)
    print("---模型首次输出---")
    print(response)
    if(response.tool_calls is not None):
        tool_call = response.tool_calls[0]
        if(tool_call.function.name == 'calculate'):
            args = json.loads(tool_call.function.arguments)
            result = eval(args['expression'])
            print(result)
            message.append({
                "role":"tool",
                "tool_call_id":tool_call.id,
                "role":"tool",
                "content":str(result)
            })
            # 再次的调用大模型
            print("最终输出")
            print(get_completion(message).content)

    
if __name__ == '__main__':
    startChat()


